package com.datastructure.test.addlinklist;

public class AddLinkedList {


    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        listNode.next=new ListNode(2);
        listNode.next.next=new ListNode(3);
        AddLinkedList addLinkedList = new AddLinkedList();
        ListNode reverseList = addLinkedList.ReverseList(listNode);
        System.out.println(reverseList);
    }
    //翻转链表
    public ListNode ReverseList(ListNode pHead) {
        ListNode res = null;
        ListNode cur = pHead;
        while(cur != null){
            ListNode temp = cur.next;
            cur.next = res;
            res = cur;
            cur = temp;
        }
        return res;
    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        ListNode l1 = ReverseList(head1);//翻转链表l1
        ListNode l2 = ReverseList(head2);//翻转链表l2
        ListNode res = null;// 用于返回的链表
        int cnt = 0;//如果两个值的加和>10，就会产生进位，这个用来存储进位
        while(l1 != null || l2 != null){
            int x1 = l1==null? 0 : l1.val;
            int x2 = l2==null? 0 : l2.val;
            int sum = x1 + x2 + cnt;//当前这一位的总和
            cnt = sum / 10;//查看当前加和是否有进位
            ///进行当前节点的插入
            ListNode tempNode = new ListNode(sum % 10);
            tempNode.next = res;
            res = tempNode;
            l1 = l1==null? null: l1.next;
            l2 = l2==null? null: l2.next;
        }
        ///如果cnt>0那么就说明存在进位还得插入一个节点
        if(cnt > 0){
            ListNode tempNode = new ListNode(cnt);
            tempNode.next = res;
            res = tempNode;
        }
        return res;

    }
}
class ListNode {
    int val;
    ListNode next = null;

    public ListNode(int val) {
        this.val = val;
    }
}